package com.chat.datea.ui;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chat.datea.R;
import com.chat.datea.base.BaseActivity;
import com.chat.datea.bean.MusicList;
import com.chat.datea.fragment.MoreFragment;
import com.chat.datea.service.DownLoderInterface;
import com.chat.datea.service.DownLoderService;
import com.chat.datea.service.IConstants;
import com.chat.datea.service.MusicInterface;
import com.chat.datea.service.MusicService;
import com.chat.datea.ui.musicpupwindow.MusicPupWindow;
import com.chat.datea.utils.exitapplication.ExitApplication;
import com.chat.datea.utils.time.Time;

import java.io.File;
import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by dllo on 15/10/22.
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, IConstants,MoreFragment.Stop {
    private static MusicInterface mi;
    private long exitTime = 0;
    private FragmentManager fManager = null;
    private static ImageView play;
    private ImageView next;
    private MyServiceConn conn;
    private Intent intent;
    private static CircleImageView music_img;
    private ImageView bj, list;
    private static MusicPupWindow musicPupWindow;
    private static TextView music_name, music_singer, music_time, music_timeAll;
    private static Activity activity;
    private Intent downloadIntent;
    private static DownLoderInterface downLoderInterface;
    private DownloadConnacition downloadConnacition;
    private static final String modeName[] = {"列表循环", "顺序播放", "随机播放", "单曲循环"};
    private int modeDrawable[] = {R.drawable.bt_list_roundplay,
            R.drawable.bt_list_order, R.drawable.bt_list_random,
            R.drawable.bt_list_roundsingle}; // 退出程序

    private int mCurMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ExitApplication.getInstance().addActivity(this);
        activity = this;
        intent = new Intent(this, MusicService.class);
        startService(intent);
        conn = new MyServiceConn();
        bindService(intent, conn, BIND_AUTO_CREATE);


        downloadIntent = new Intent(this, DownLoderService.class);
        startService(downloadIntent);
        downloadConnacition = new DownloadConnacition();
        bindService(downloadIntent, downloadConnacition, BIND_AUTO_CREATE);


        fManager = getSupportFragmentManager();
        MainFragment mainFragment = new MainFragment(fManager);
        FragmentTransaction ft = fManager.beginTransaction();
        ft.replace(R.id.fl_content, mainFragment);
        ft.commit();
        initView();

    }

    @Override
    public void stop() {
        stopService(intent);
        Log.e("MainActivity", "停止了");
        mi.go();
    }



    class DownloadConnacition implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downLoderInterface = (DownLoderInterface) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    public static void download(String path, File savDir) {
        if (downLoderInterface != null) {
            downLoderInterface.downLoder(path, savDir);
        }
    }


    public static Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Bundle bundle = msg.getData();
            int duration = bundle.getInt("duration");
            int currentPostition = bundle.getInt("currentPosition");
            int position = bundle.getInt("position");
            init();
            music_timeAll.setText(Time.formatTime((long) duration));
            music_time.setText(Time.formatTime((long) currentPostition));
            if (musicPupWindow != null) {
                musicPupWindow.add(position);
                musicPupWindow.getImg();
            }
        }
    };


    private static void init() {
        if (mi.getIsPlay()) {
            play.setImageResource(R.mipmap.bt_minibar_pause_normal);
        } else {
            play.setImageResource(R.mipmap.bt_minibar_play_normal);
        }
        music_img.setImageBitmap(mi.getRadioUrl());
        music_name.setText(mi.getName());
        music_singer.setText(mi.getSinger());
    }


    private void initView() {
        play = (ImageView) findViewById(R.id.play);
        next = (ImageView) findViewById(R.id.next);
        music_name = (TextView) findViewById(R.id.music_name);
        music_singer = (TextView) findViewById(R.id.music_singer);
        music_time = (TextView) findViewById(R.id.music_time);
        music_timeAll = (TextView) findViewById(R.id.music_timeAll);
        music_img = (CircleImageView) findViewById(R.id.music_img);
        list = (ImageView) findViewById(R.id.list);
        bj = (ImageView) findViewById(R.id.bj);
        play.setOnClickListener(this);
        next.setOnClickListener(this);
        bj.setOnClickListener(this);
        list.setOnClickListener(this);

    }


    /**
     * sdcard/download/music
     */
    //点击回退键的处理：判断Fragment栈中是否有Fragment
    //没，双击退出程序，否则像是Toast提示
    //有，popbackstack弹出栈
    @Override
    public void onBackPressed() {
        if (fManager.getBackStackEntryCount() == 0) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }

        } else {
            fManager.popBackStack();
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.play:
                if (mi.getIsPlay()) {
                    mi.pause();
                } else if (mi.getIsPlay() == false && mi.getDuration() > mi.getProgress()) {
                    mi.continuePlay();
                }
                break;
            case R.id.next:
                mi.next();
                break;
            case R.id.bj:
                Intent intent = new Intent(this, MusicActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_in_stop);
                break;

            case R.id.list:
                musicPupWindow = new MusicPupWindow(activity, linster, mi.getList(), mi.getPosition(), mi.getmPlayMode());
                musicPupWindow.showAtLocation(MainActivity.this.findViewById(R.id.fl_content), Gravity.CENTER, 0, 0); //设置layout在PopupWindow中显示的位置
                //显示窗口
                break;
        }

    }




    public static void clean() {
        music_name.setText("音约,与你的约定");
        music_singer.setText("");
        music_time.setText("00:00");
        music_timeAll.setText("00:00");
        music_img.setImageResource(R.mipmap.icon_cover_small);
        mi.stop();
        play.setImageResource(R.mipmap.bt_minibar_play_normal);
    }

    private View.OnClickListener linster = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.clean:

                    break;
                case R.id.type:
                    changeMode();
                    break;
            }

        }
    };

    private void changeMode() {
        mCurMode = mi.getmPlayMode();
        mCurMode++;
        if (mCurMode > MPM_SINGLE_LOOP_PLAY) {
            mCurMode = MPM_LIST_LOOP_PLAY;
        }
        mi.setPlayMode(mCurMode);
        initPlayMode();
    }

    private void initPlayMode() {
        Toast.makeText(this, modeName[mCurMode], Toast.LENGTH_SHORT).show();
        musicPupWindow.getImg().setImageResource(modeDrawable[mCurMode]);
    }


    class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mi = (MusicInterface) service;
            mi.go();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

    }

    public static void play(ArrayList<MusicList> lists, int position) {
        mi.play(lists, position);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mi != null) {
            mi.background();
        }
        unbindService(conn);
        unbindService(downloadConnacition);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }
}
